from django.contrib import admin

# Register your models here.
from django.contrib import admin
from celery_tasks.html.tasks import generate_static_list_search_html, generate_static_sku_detail_html
from . import models


class GoodsCategoryAdmin(admin.ModelAdmin):
    """商品类别模型站点管理类"""
    def save_model(self, request, obj, form, change):
        """
        当调用admin中的保存按钮时来调用此方法
        request: 保存本次请求对象
        obj: 本次要保存的模型对象
        form: admin中表单
        change: 是否改动
        """
        obj.save()
        #重新生成的列表静态页面
        generate_static_list_search_html.delay()

    def delete_model(self, request, obj):
        """
        当在admin站点中 点击商品分类的删除时,会调用此方法
        :param request: 本次删除时的请求
        :param obj: 本次要删除的模型对象
        :return:
        """
        obj.delete()
        # 重新生成的列表静态页面
        # from celery_tasks.html.tasks import generate_static_list_search_html
        generate_static_list_search_html.delay()

class SKUAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()

        generate_static_sku_detail_html.delay(obj.id)


class SKUImageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.sku.id)

        # 设置SKU默认图片
        sku = obj.sku
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            sku.save()

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        generate_static_sku_detail_html.delay(sku_id)


admin.site.register(models.Brand)
admin.site.register(models.Goods)
admin.site.register(models.GoodsCategory, GoodsCategoryAdmin) #注意要添加站点管理类，不然无法调用celery
admin.site.register(models.GoodsChannel)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUImage, SKUImageAdmin)
admin.site.register(models.SKUSpecification)
admin.site.register(models.SpecificationOption)